package com.lily.aidouzixun.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.text.Html;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.activity.DynamicCollectActivity;
import com.lily.aidouzixun.activity.DynamicMineActivity;
import com.lily.aidouzixun.activity.LoginActivity;
import com.lily.aidouzixun.activity.UserDetailActivity;
import com.lily.aidouzixun.bean.UserInfo;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.CircleImageView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.DataConverter;
import com.lily.aidouzixun.util.FileManager;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.MyConstant.DataType;
import com.lily.aidouzixun.util.MyConstant.IntentForResultCODE;
import com.lily.aidouzixun.util.MyConstant.IntentKey;
import com.lily.aidouzixun.util.MyConstant.RequireParams;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * 用户中心Fragment
 */
public class UserCenterFragment extends Fragment{
    private static final String TAG = "UserCenterFragment";

    private TitleBar mTitleBar; //标题栏
    //private CustomImageView civUserAvatar;  //用户头像
    private CircleImageView civUserAvatar;  //用户头像
    //private ImageView civUserAvatar;  //用户头像
    private RelativeLayout rlNameAccount;   //用户昵称和账号
    private TextView tvUserNickname;    //用户昵称
    private TextView tvUserAccount; //用户账号
    private TextView tvUserPoint;   //用户积分
    private ImageView ivUserDetail; //跳转到用户详情页
    private RelativeLayout rlUser;  //用户信息包裹布局
    private TextView tvUnLogin; //登录注册

    private RelativeLayout rlPoint; //积分
    private RelativeLayout rlMineDiscuss;
    private RelativeLayout rlCollect;  //收藏
    private Button bnQuitLogin; //退出登录

    private String key; //key,一般为hascode,作为Map中的key值
    private Context mContext;
    private Activity mActivity;
    private static final String USER_KEY = "userDetailInfo";  //现场保护和恢复key
    private static final String TITLE = "用户中心";
    private static MyHandler mHandler; //自定义的Handler，用于发送和接收消息
    private UserInfo mUserInfo  = new UserInfo(); //用户信息
    private String avatarPath;  //头像在本地的路径
    private Bitmap avatarBitmap;
    private final static String[] setAvatarItems = new String[] {"选择本地照片", "拍照"};
    /**
     * 头像名称
     */
    private static final String IMAGE_FILE_NAME =  "avatar.jpg";

    /**
     * 当一个Fragment关联到一个Activit时调用
     * @param activity
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    /**
     * 初始创建Fragment对象时调用
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        backingOut(savedInstanceState); //现场恢复
        init(); //初始化
    }

    /**
     * 创建Fragment对象相关的View视图时调用
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        L.i(TAG, "onCreateView");
        if(container == null) return null;
        backingOut(savedInstanceState);  //现场恢复
        View view = inflater.inflate(R.layout.usercenter_fragment, container, false);
        findViews(view);
        setListeners();

        return view;
    }

    /**
     * 当Activity对象完成自己的onCreate方法时被调用
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * Fragment对象在UI可见时调用
     */
    @Override
    public void onStart() {
        super.onStart();
    }

    /**
     * Fragment对象的UI可以与用户交互时调用
     * 加载数据
     */
    @Override
    public void onResume() {
        super.onResume();
        try {
            //清除Glide缓存
            Glide.get(mContext).clearMemory();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Glide.get(mContext).clearDiskCache();
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Fragment对象完成清理View资源时调用
     * 在 activity 被销毁前会调用该方法
     * 1.调用了 finish 方法使得当前activity 正在关闭
     * 2.系统为了保护内存临时释放这个 activity的实例，而调用该方法。
     * 可以用 isFinishing 方法来区分这两种不同的情况。
     * 按home键不会调用
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消任务
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_CANCEL, this.key + DataType.USERCENTER_INFO);
        MessageDispatcher.sendMessage(MyApplication.getHandler(),MessageType.REQUIRE_CANCEL,this.key + DataType.UPLOAD_AVATAR);
        MessageDispatcher.sendMessage(MyApplication.getHandler(),MessageType.REQUIRE_CANCEL,this.key + DataType.USER_SIGN);
    }

    /**
     * Fragment对象没有与Activity对象关联时调用
     */
    @Override
    public void onDetach() {
        super.onDetach();
    }

    /**
     * 得到控件
     * @param view
     */
    private void findViews(View view) {
       mTitleBar = (TitleBar) view.findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperationVisible(false);
        mTitleBar.setRightOperation("签到", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userSign();
                //T.longToast(mContext, "功能暂时没有实现！");
            }
        });
        //用户信息
        rlUser = (RelativeLayout) view.findViewById(R.id.user_rl);
        rlNameAccount = (RelativeLayout) view.findViewById(R.id.name_account_rl);
        civUserAvatar = (CircleImageView) view.findViewById(R.id.user_avatar);
        //civUserAvatar = (CustomImageView) view.findViewById(R.id.user_avatar);
        //civUserAvatar = (ImageView) view.findViewById(R.id.user_avatar);
        tvUserNickname = (TextView) view.findViewById(R.id.user_nickname);
        tvUserAccount = (TextView) view.findViewById(R.id.user_account);
        tvUserPoint = (TextView) view.findViewById(R.id.tv_user_point);
        ivUserDetail = (ImageView) view.findViewById(R.id.user_detail);
        //未登陆
        tvUnLogin = (TextView) view.findViewById(R.id.unlogin_tv);
        tvUnLogin.setText(Html.fromHtml("<u>请登录 / 注册</u>"));
        rlPoint = (RelativeLayout) view.findViewById(R.id.rl_point);
        rlMineDiscuss = (RelativeLayout) view.findViewById(R.id.rl_discuss_mine);
        rlCollect = (RelativeLayout) view.findViewById(R.id.rl_collection);
        bnQuitLogin = (Button) view.findViewById(R.id.bn_quitlogin);
        if (!MyConfig.isLogined(mContext)) {
            //没有登陆
            processUnLogin();
        } else {
            //处理登陆
            mUserInfo = MyConfig.getUserInfo(mContext);
            getUserInfo(); //重新得到用户数据
        }
    }
    /**
     * 接收回传信息，通过MainActivity调用转发
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case IntentForResultCODE.LOGIN_REQUESTCODE:
                    processLogined();
                    break;
                case IntentForResultCODE.MODIFY_AVATAR_BY_IMAGE_REQUESTCODE:    //通过图片修改头像
                    if (data != null) {
                        Uri avatarUri = data.getData();
                        if (Validator.isEffective(avatarUri.toString())) {
                            avatarPath = DataConverter.getRealPathFromURI(mContext, avatarUri);
                            startPhotoZoom(data.getData());
                        }
                    }
                    break;
                case IntentForResultCODE.MODIFY_AVATAR_BY_CAMERA_REQUESTCODE:    //通过拍照修改头像
                    if (HardWare.hasSdcard()) {
                        avatarPath = FileManager.AVATAR_PATH;
                        File avatar = new File(avatarPath);
                        if (avatar != null) {
                            startPhotoZoom(Uri.fromFile(avatar));
                        }
                    } else {
                        T.longToast(mContext, "未找到存储卡，无法存储照片！");
                    }
                    break;
                case IntentForResultCODE.PHOTO_ZOOM_REQUESTCODE:    //缩放图片
                    if (data != null) {
                        setAvatarByIntent(data);    //设置头像
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过intent设置头像
     * @param data
     */
    private void setAvatarByIntent(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            //把裁剪好的照片保存到本地
            avatarBitmap = extras.getParcelable("data");
            DataConverter.getFilePathByBitmap(avatarBitmap, MyConstant.AVATAR_PATH, DataType.UPLOAD_AVATAR);
        }
    }

    /**
     * 通过文件路径设置头像
     */
    private void setAvatarByFilePath() {
        File file = new File(MyConstant.AVATAR_PATH);
        if (file.isFile() && file.length() > 0) {
            Bitmap bitmap = BitmapFactory.decodeFile(MyConstant.AVATAR_PATH);
            civUserAvatar.setImageBitmap(bitmap);
        }
    }

    /**
     * 上传用户头像
     * @param avatarPath
     */
    private void uploadAvatar(String avatarPath){
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        if (!Validator.isEffective(avatarPath)) {
            return;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.UPLOAD_AVATAR);
        param.put(MyConstant.RequireParams.PHOTO_PATH, avatarPath);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.UPLOAD_AVATAR);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    public static MyHandler getMyHandler() {
        return mHandler;
    }

    /**
     * 裁剪图片方法实现
     */
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //设置裁剪
        intent.putExtra("crop", "true");
        //aspectX,aspectY 宽高比
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        getActivity().startActivityForResult(intent, IntentForResultCODE.PHOTO_ZOOM_REQUESTCODE);
    }

    /**
     * 处理已经登录的方法
     */
    private void processLogined() {
        if (MyConfig.isLogined(mContext)) {
            tvUnLogin.setVisibility(View.GONE);
            rlNameAccount.setVisibility(View.VISIBLE);
            //设置头像
            /*if (Validator.isEffective(mUserInfo.getAvatarUrl())) {
                Glide.with(mContext).load(mUserInfo.getAvatarUrl()).placeholder(R.mipmap.default_avatar).into(civUserAvatar);
            }*/

            String nickName = mUserInfo.getNickname();
            if (Validator.isEffective(nickName)) {
                tvUserNickname.setText(nickName);
            } else {
                tvUserNickname.setText("请设置昵称");
            }
            switch (mUserInfo.getLoginFrom()) {
                case UserInfo.UserType.USERNAME_PWD:
                    String account = mUserInfo.getUsername();
                    tvUserAccount.setText(account);
                    break;
                case UserInfo.UserType.QQ:
                    tvUserAccount.setText("QQ登录用户");
                    break;
                case UserInfo.UserType.PHOME_SMS:
                    tvUserAccount.setText(mUserInfo.getLoginPhone());
                    break;
            }
            tvUserPoint.setVisibility(View.VISIBLE);
            tvUserPoint.setText(mUserInfo.getPoint() + "积分");
            ivUserDetail.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 没有登录
     */
    private void processUnLogin() {
        rlNameAccount.setVisibility(View.GONE);
        tvUserPoint.setVisibility(View.GONE);
        ivUserDetail.setVisibility(View.GONE);
        tvUnLogin.setVisibility(View.VISIBLE);
    }



    /**
     * 现场恢复
     * @param savedInstanceState
     */
    public void backingOut(Bundle savedInstanceState) {
        if(savedInstanceState != null) {
        }
    }
    /**
     * 初始化方法
     */
    private void init() {
        key = "" + this.hashCode();
        mContext = getActivity();
        mActivity = getActivity();
        mHandler = new MyHandler(UserCenterFragment.this);
        MyConfig.getInstance(mContext).registerHandler(this.hashCode(), mHandler);
        //清除Glide缓存
        Glide.get(mContext).clearMemory();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(mContext).clearDiskCache();
            }
        }).start();

    }


    /**
     * 设置监听
     */
    private void setListeners() {
        //用户信息父布局
        rlUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    Intent intent = new Intent(mContext, UserDetailActivity.class);
                    Bundle bundle = new Bundle();
                    //测试数据
                    bundle.putString(IntentKey.BACK_TITLE, TITLE);
                    if (mUserInfo != null) {
                        bundle.putParcelable(IntentKey.USER_INFO,mUserInfo);
                    }
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    gotoLoginActivity();
                }
            }
        });
        //用户头像
        civUserAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    showSetAvatarDialog();  //修改用户头像
                } else {
                    T.shortToast(mContext, "请先登录！");
                    gotoLoginActivity();
                }
            }
        });

        //登录按钮监听
        tvUnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gotoLoginActivity();
            }
        });
        //我的关注
        rlMineDiscuss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    Intent intent = new Intent(mContext, DynamicMineActivity.class);
                    intent.putExtra(IntentKey.BACK_TITLE, TITLE);
                    startActivity(intent);
                } else {
                    T.shortToast(mContext, "请先登录！");
                    gotoLoginActivity();
                }
            }
        });

        //收藏
        rlCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    Intent intent = new Intent(mContext, DynamicCollectActivity.class);
                    intent.putExtra(IntentKey.BACK_TITLE, TITLE);
                    startActivity(intent);
                } else {
                    T.shortToast(mContext, "请先登录！");
                    gotoLoginActivity();
                }
            }
        });

    }

    /**
     * 跳转到登录界面
     */
    private void gotoLoginActivity() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(IntentKey.BACK_TITLE, TITLE);
        startActivityForResult(intent, IntentForResultCODE.LOGIN_REQUESTCODE);
    }

    /**
     * 用户签到
     */
    private void userSign() {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        if (!Validator.isEffective(MyConfig.getUserId(mContext))) {
            T.shortToast(mContext, "请先登录");
            gotoLoginActivity();
        } else  {
            ArrayMap<String, Object> param = new ArrayMap<String, Object>();
            param.put(RequireParams.DATA_TYPE, DataType.USER_SIGN);
            param.put(RequireParams.MAP_KEY, this.key + DataType.USER_SIGN);
            param.put(RequireParams.CALL_BACK_HANDLER, mHandler);
            MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
        }
    }

    /**
     * 显示设置头像的对话框
     */
    private void showSetAvatarDialog() {
        new AlertDialog.Builder(mContext)
                .setTitle("设置头像")
                .setItems(setAvatarItems, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        switch (which) {
                            case 0:     //本地选取
                                Intent filePhotoIntent = new Intent();
                                filePhotoIntent.setType("image/*");
                                filePhotoIntent.setAction(Intent.ACTION_GET_CONTENT);
                                getActivity().startActivityForResult(filePhotoIntent, IntentForResultCODE.MODIFY_AVATAR_BY_IMAGE_REQUESTCODE);
                                break;
                            case 1:
                                if (HardWare.hasSdcard()) {
                                    //删除临时文件
                                    FileManager.deleteFile(FileManager.AVATAR_PATH);
                                    Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intentFromCapture.putExtra(
                                            MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(FileManager.AVATAR_PATH)));
                                    getActivity().startActivityForResult(intentFromCapture,
                                            IntentForResultCODE.MODIFY_AVATAR_BY_CAMERA_REQUESTCODE);
                                } else {
                                    T.longToast(mContext, "未找到存储卡，无法存储照片！");
                                }
                                break;
                            default:
                                break;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    /**
     * 得到初始化信息
     */
    private void getUserInfo() {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        if(MyConfig.isLogined(mContext)) {  //用户已经登录，获得用户信息
            ArrayMap<String, Object> param = new ArrayMap<String, Object>();
            param.put(RequireParams.DATA_TYPE, DataType.USERCENTER_INFO);
            param.put(RequireParams.URID, mUserInfo.getUrid());
            param.put(RequireParams.MAP_KEY, this.key + DataType.USERCENTER_INFO);
            param.put(RequireParams.CALL_BACK_HANDLER, mHandler);
            MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
        }
    }
    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Fragment>  mFragmentReference;

        /**
         * 构造方法，传递fragment对象，防止内存泄露
         * @param fragment
         */
        MyHandler(Fragment fragment) {
            mFragmentReference = new WeakReference<Fragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final UserCenterFragment fragment = (UserCenterFragment) mFragmentReference.get();
                if(fragment !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.USERCENTER_INFO) { //得到用户信息
                                //每次进入，都得到用户最新数据
                                SparseArray<Object> userinfoResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) userinfoResult.get(0);
                                if ("0".equals(errno)) {  //得到数据成功
                                    fragment.mUserInfo = (UserInfo) userinfoResult.get(2);
                                    if (fragment.mUserInfo != null) {
                                        //把用户信息保存起来
                                        MyConfig.setUserInfo(fragment.mContext, fragment.mUserInfo);
                                        fragment.processLogined();    //得到信息成功的处理
                                    }
                                } else if ("1".equals(errno)) { //得到信息失败的处理

                                }
                            } else if (DataType.UPLOAD_AVATAR == msg.arg1) {    //上传头像成功
                                fragment.getUserInfo(); //重新得到用户数据
                            } else if (msg.arg1 == DataType.USER_SIGN) {    //用户签到
                                SparseArray<Object> signResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) signResult.get(0);
                                if ("0".equals(errno)) {  //签到成功
                                    T.shortToast(fragment.mContext, "签到已成功 +5 积分！");
                                    fragment.getUserInfo();
                                } else if ("1".equals(errno)) { //今天已经签过到了
                                    T.shortToast(fragment.mContext, "今天已经签过到了，明天再来！");
                                } else if ("2".equals(errno)) {
                                    T.shortToast(fragment.mContext, "签到失败");
                                }
                            }
                            break;
                        case MessageType.LOGIN_STATUS_CHANGED:  //登录状态改变
                            if (!MyConfig.isLogined(fragment.mContext)) {
                                //没有登陆
                                fragment.processUnLogin();
                            } else {
                                //处理登陆
                                fragment.mUserInfo = MyConfig.getUserInfo(fragment.mContext);
                                fragment.getUserInfo(); //重新得到用户数据
                            }
                            break;
                        case MessageType.SAVE_AVATAR_FINISHED:  //头像保存成功
                            int dataType = (int) msg.obj;
                            if (DataType.UPLOAD_AVATAR == dataType) {   //上传头像
                                File avatar = new File(MyConstant.AVATAR_PATH);
                                if (!avatar.isFile()) {
                                    return;
                                }
                                //设置头像到服务器
                                fragment.uploadAvatar(MyConstant.AVATAR_PATH);
                            } else if (DataType.USERCENTER_INFO == dataType) {
                                fragment.setAvatarByFilePath();
                            }

                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




}
